{% extends "wallet/components/wallet_tab.jinja" %}
{% include "includes/file-uploader.html" %}
{% include "includes/dnd-textarea.html" %}
{% include "includes/hwi/hwi.jinja" %}
{% set tab = 'settings' %}

{% block content %}
	<nav class="mb-8 text-center text-dark-200 border-b border-dark-600">
		<ul class="flex flex-wrap -mb-px">
			<li id="info_settings_tab_btn" aria-checked="true" class="mr-2 py-2 border-b-2 border-transparent aria-checked:text-link aria-checked:border-b-2 aria-checked:border-link" id="automatic_menu_item">
				<button type="button" class="text-lg inline-block py-1 px-3 hover:text-white rounded-lg hover:bg-dark-700" onclick="setSettingsView('info')"> {{ _("Wallet Info") }} </button>
			</li>
			<li id="export_settings_tab_btn" aria-checked="false" class="mr-2 py-2 border-b-2 border-transparent aria-checked:text-link aria-checked:border-b-2 aria-checked:border-link" id="automatic_menu_item">
				<button type="button" class="text-lg inline-block py-1 px-3 hover:text-white rounded-lg hover:bg-dark-700" onclick="setSettingsView('export')"> {{ _("Export") }} </button>
			</li>
			<li id="advanced_settings_tab_btn" aria-checked="false" class="mr-2 py-2 border-b-2 border-transparent aria-checked:text-link aria-checked:border-b-2 aria-checked:border-link" id="automatic_menu_item">
				<button type="button" class="text-lg inline-block py-1 px-3 hover:text-white rounded-lg hover:bg-dark-700" onclick="setSettingsView('advanced')"> {{ _("Advanced") }} </button>
			</li>
		</ul>
	</nav>

	<div id="wallet_info_settings_tab">
		{% if wallet.is_multisig %}
			<h3>{{ _("Devices") }}</h3>
        	{% if has_device_for_multisig_registration %}
				<p>Register Multisig</p>
				<div class="flex flex-col mt-1 mb-2">
					{% for device in wallet.devices %}
						{% if device.supports_multisig_registration %}
							{% for wallet_key in wallet.keys %}
								{% set matching_device_key = device.keys | selectattr("fingerprint", "eq", wallet_key.fingerprint) | first %}
                   				{% if matching_device_key %}
                        			<button class="button p-1" type="button" onclick="registerMultisigOnDevice('{{ matching_device_key.fingerprint }}');">Register on {{ device.name }}</button>
                    			{% endif %}
							{% endfor %}
						{% endif %}
					{% endfor %}
				</div>
			{% endif %}
			<p>{{ wallet.sigs_required }} out of {{ wallet.keys|length }} multisig</p>
		{% else %}
			<h3>{{ _("Device") }}</h3>
		{% endif %}

		<div class="grid grid-cols-2 gap-3">
			{% for device in wallet.devices %}
				<a href="{{ url_for('devices_endpoint.device', device_alias=device.alias) }}">
					<div class="selection">
						<p></p>
						<img src="{{ url_for(device.blueprint(), filename=device.icon) }}" width="18px">
						<p>{{ device.name }}</p>
					</div>
				</a>
			{% endfor %}
		</div>

		<button onclick="toggleKeysList()" id="toggle_keys_list" type="button" class="button mt-3">{{ _("Show keys details") }}</button>

		<div id="keys_list" style="display: none">
			<h3 class="mt-8">{{ _("Slip-132") }}</h3>
			<p>{{ _("SLIP-132 extended public keys (xpubs) are a different format for xpubs which usually starts with zpub or ypub.") }}</p>
			<label class="flex space-x-1 items-center">
				<input type="checkbox" id="use_slip_132" onchange="toggleKeyDisplay()">
				<label for="use_slip_132">{{ _("Use SLIP-132") }}</label>
			</label>

			{% for i in range(wallet.devices | length) %}
				{% set device = wallet.devices[i] %}
				{% set key = wallet.keys[i] %}
				<h3 class="mt-8">{{ _("Signer") }} {% if wallet.is_multisig %}{{ loop.index }} {% endif %}- {{ device.name }}</h3>
				<div class="table-holder">
					<table>
						<thead>
							<tr>
								<th>{{ _("Network") }}</th>
								<th>{{ _("Purpose") }}</th>
								<th class="optional">{{ _("Derivation") }}</th>
								<th class="optional table-key">{{ _("Key") }}</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td>
									{% include "components/network_label.jinja" %}
								</td>
								<td>{{ purposes[key.key_type] }}</td>
								<td class="optional">{{ key.derivation }}</td>
								<td class="scroll xpub optional"><div class="table-key normal_xpub hidden">{{ key.original }}</div><div class="table-key slip132_xpub">{{ key.xpub }}</div></td>
							</tr>
						</tbody>
					</table>
				</div>	
			{% endfor %}
		</div>
	</div>

	<div class="hidden" id="wallet_export_settings_tab">
		<div>

			{% set supports_export_to_device = [] %}
			{% for device in wallet.devices if device.exportable_to_wallet %}
				{# check if export_wallet is not None #}
				{% if device.export_wallet(wallet) %}
					{% set supports_export_to_device = supports_export_to_device.append(device) %}
				{% endif %}
			{% endfor %}

			{% if supports_export_to_device != [] %}
				<h3>{{ _("Export wallet to device") }}</h3>
				<p>
					{{ _("Export this wallet to a device by scanning its QR code or importing its data file.") }}
				</p>

				{% for device in wallet.devices %}
					{% if device.exportable_to_wallet %}
						{% if device.wallet_export_type == 'file' %}
							<a 
							download="{{ wallet.name | ascii20 }}.txt"
							href="data:text/plain;charset=US-ASCII,{{ device.export_wallet(wallet) }}"
							{% if device.device_type == 'coldcard' %}
								onclick="showNotification(`{{ _('Import wallet file to your ColdCard: Settings -> Multisig Wallets -> Import from SD') }}`, 0)"
							{% endif %}
							class="button mt-3">
								Save {{ device.name }} file
							</a>
						{% elif device.wallet_export_type == 'qr' %}
							<button onclick="showPageOverlay('{{ device.alias }}_export_qr_code')" type="button" class="button mt-3 mb-8">Show {{ device.name }} QR Code</button>
							<div id="{{ device.alias }}_export_qr_code" class="bg-dark-800 p-4 w-120" style="display: none;">
								<div class="flex justify-between mb-4">
										<h3 class="mb-0">{{ _("Scan this with your") }} {{ device.name }} {{ _("device") }} </h3>
										<p class="m-0 cursor-pointer" onclick="hidePageOverlay()" class="cursor-pointer">Close</p>
								</div>
								<qr-code value="{{ device.export_wallet(wallet) }}" width="400"></qr-code>
							</div>
						{% endif %}
					{% endif %}
				{% endfor %}
			{% endif %}
			
			<h3>{{ _("Export to wallet software") }}</h3>
			<p>{{ _("Export this wallet to another Specter instance or other supported wallet softwares by scanning the QR code or importing the JSON file.") }}</p>
			<button onclick="showPageOverlay('account_map_export', null, 'start')" type="button" class="button mt-3" data-cy="show-export-details-overlay-btn">{{ _("Go to export details") }}</button>

			<h3 class="mt-8">{{ _("Specter wallet backup") }}</h3>
			<p>{{ _("Create a JSON file containing all wallet data including labels.") }}</p>
			<a download="{{ wallet.name }}.json" class="button mt-3" id="export_specter_format">Download Specter JSON file</a>

			<h3 class="mt-8">{{ _("Printable PDF backup") }}</h3>
			<p>
				{{ _("It is recommended that you print this backup and save it with each of your devices.") }}
				<tool-tip width="180px">
						<span slot="paragraph">
							{{ _("This backup includes all the information you need to restore your wallet in Specter Desktop or other compatible wallets including Bitcoin Core.") }}
							{{ _("It is recommended that you keep this file private. It contains all the information to track your balance and associate transactions with your wallet.") }}
						</span>
				</tool-tip>
			</p>
			<button id="pdf-wallet-download" type="button" class="button mt-3">Open backup PDF</button>

			<span id="advanced_pdf_export_toggle" onclick="togglePDFExportAdvanced()">{{ _("Adjust PDF backup (advanced)") }} &#9654;</span>
			<div class="hidden" id="advanced_pdf_export_container">
				<div>
					<label data-style="font-size: 1em;">{{ _("Use SLIP-132 for xpubs in PDF:") }}&nbsp;</label>
					<label class="switch">
						<input type="checkbox" id="use_slip_132_pdf" data-style="margin: auto;" onchange="toggleKeyDisplay()">
						<span class="slider"></span>
					</label>
				</div>
			</div>

			{% if not wallet.is_multisig %} 
				<h3 class="mt-8">{{ _("Uncle Jim PDF") }}</h3>
				<p>
					{{ _("PDF optimized for Uncle Jims: hand out addresses to receive funds for friends & family without hardware wallet.") }}
					<tool-tip width="180px">
							<span slot="paragraph">
							{{ _('The PDF lists many singlesig addresses in QR code format, as well as the descriptor of the wallet as a QR code with which the wallet can be imported to Specter Desktop at any time.') }}
							{{ _('There are checkboxes to keep track of which addresses were used already.') }}
							{{ _('Can be folded into DIN-A5 to fit in a transparent sealing bag (together with the seed).') }}
							</span>
					</tool-tip>
				</p>
				<button id="pdf-paperxpub-download" type="button" class="button mt-3">Get Uncle Jim PDF</button>
			{% endif %}

			{% include 'wallet/components/wallet_pdf.jinja' %}
			{% include "wallet/settings/components/export_wallet_account_map.jinja" %}
		</div>
	</div>

	<div class="hidden" id="wallet_advanced_settings_tab">
		<div>
			<h3>{{ _("Import address labels (Electrum or Specter)") }}</h3>

			<form action="./importaddresslabels" method="POST" class="padded" data-style="max-width: 500px">
				<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
				<div>
					<dnd-textarea 
						name="address_labels_data" 
						id="address_labels_data" 
						placeholder="{{ _('You can paste and drag & drop here: ') }}{{ _('Electrum JSON file, Specter addresses CSV or Specter JSON file') }}"  
						textarea-style="margin-bottom: 10px;"
					>
					</dnd-textarea>

					<div class="flex justify-between">
						<file-uploader class="button" id="label-uploader" image_src="{{ url_for('static', filename='img/file.svg') }}" image_width="30px">
							<span slot="description">Upload File</span>
						</file-uploader>
						<button type="submit" name="action" value="import_address_labels" class="button bg-accent text-white" data-style="max-width: 130px; margin-left: 20px">{{ _("Import") }}
							<tool-tip width="200px">
								<span slot="paragraph">
									{{ _('The expected format for Electrum contains:') }}<br>
									{{ _('{"8a5e4...": "some tx id label", "bc1qj3...": "some address label"}') }}<br><br>
									{{ _('The expected format for Specter JSON contains:') }}<br>
									{{ _('{"labels": {"some_label": ["bc1qj3..."], ...}') }}<br><br>
									{{ _('The expected format for Specter CSV contains:') }}<br>
									{{ _('Address,Label') }}<br>
									{{ _('bc1qj3...,some_label') }}<br> 
								</span>
							</tool-tip>
						</button>
					</div>
				</div>
			</form>

			<div class="section-separator"></div>
			<h3 class="mt-8">{{ _("Keypool control") }}</h3>
			<p>{{ _("You're currently watching") }} {{ wallet.keypool }} {{ _("receiving addresses, and") }} {{ wallet.change_keypool }} {{ _("change addresses.") }}</p>
			<form action="./keypoolrefill" method="POST" class="padded" data-style="max-width: 500px">
				<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
				<div class="floating-wrapper my-3">
					<input class="floating-input peer" placeholder=" " type="number" name="keypooladd" value="100" step="1">
					<label class="floating-label">More Addresses To Watch</label>
				</div>
				<button type="submit" name="action" value="keypoolrefill" class="button">{{ _("Add") }}</button>
			</form>

			<h3 class="mt-8" id="blockchain-rescan">{{ _("Blockchain rescan") }}</h3>
			<p>
				{{ _("Rescan the blockchain or unspent transactions on demand.") }}
				{% if wallet.is_taproot %}
					<b>709632</b> {{ _("was the first Taproot block.") }}
				{% else %}
					<b>481824</b> {{ _("was the first Segwit block.") }}
				{% endif %}
			</p>
			<form action="./rescan" method="POST" class="padded" data-style="max-width: 500px">
				<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
				{% if wallet.rescan_progress %}
					<div class="row aligned">
						<div data-style="margin-right: 30px; flex-grow: 1;">{{ _("Rescanning blockchain:") }} <span id="{{ wallet.alias }}_wallet_rescan_percents">{{"%.2f" % (wallet.rescan_progress*100)}}</span>%</div>
						<button type="submit" name="action" value="abortrescan" class="button">{{ _("Abort rescan") }}</button>
					</div>
				{% else %}
					<div class="row aligned" data-style="justify-content: space-between;">
						{% if specter.info.chain == "main" %}
							{% if wallet.is_taproot %}
								{% set startblock=(709632 if not specter.info['pruned'] or specter.info['pruneheight'] < 709632 else specter.info['pruneheight']) %}
							{% else %}
								{% set startblock=(481824 if not specter.info['pruned'] or specter.info['pruneheight'] < 481824 else specter.info['pruneheight']) %}
							{% endif %}
						{% else %}
							{% set startblock=(0 if not specter.info['pruned'] else specter.info['pruneheight']) %}
						{% endif %}
						<div class="floating-wrapper my-3">
							<input class="floating-input peer" placeholder=" " type="number" name="startblock" value="{{startblock}}" min="{{startblock}}">
							<label class="floating-label">Block To Rescan From</label>
						</div>
						<button id="rescan-btn" type="submit" name="action" value="rescanblockchain" class="button" data-style="flex-basis: 170px; flex-grow: 0;">{{ _("Rescan") }}</button>
					</div>
					{% if specter.info['pruned']  %}
						<p class="note full-width">{{ _("Note: You are using a pruned node. Rescan is limited by the pruned height to block:") }} {{specter.info['pruneheight']}}</p>
					{% endif %}
				{% endif %}
			</form>

			<form action="./rescan" method="POST" class="padded" data-style="max-width: 500px">
				<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
				{% if specter.info["utxorescan"] %}
					<div>
						<div>{{ _("UTXO rescan in process:") }} <span id="wallet_rescan_percents">{{ "%.2f"|format(specter.info["utxorescan"]) }}</span>%.</div>
						<button type="submit" name="action" value="abortrescanutxo" class="btn" data-style="max-width: 130px; margin-left: 20px">{{ _("Abort rescan") }}</button>
					</div>
				{% else %}
					<div>
						<p>{{ _("Or rescan only unspent transactions") }}</p>
						<button id="rescan-utxo-btn" type="submit" name="action" value="rescanutxo" class="button">
							{{ _("Rescan UTXO") }}
							<tool-tip width="150px" image="note">
										<h4 slot="title">{{ _("Rescanning UTXO set") }}</h4>
										<span slot="paragraph">
									{{ _("Only unspent transactions will be imported, so you won't see the full history, but your balance will be there.") }}<br>
									<b>{{ _("Note:") }}</b> {{ _("Make sure you have enough addresses in the keypool, otherwise not all unspent transactions may be found.") }}
										</span>
								</tool-tip>
						</button>
					</div>
					{% if specter.info['pruned'] %}
						<div class="row" data-style="margin-top: 10px">
							<label for="use_explorer"><input data-style="width: auto; min-width: auto;" type="checkbox" id="use_explorer" name="use_explorer" checked> {{ _("fetch missing data from block explorer") }}
							</label>
							<tool-tip width="150px" image="note">
									<h4 slot="title">{{ _("Fetch missing data") }}</h4>
									<span slot="paragraph"
										{{ _("You are using a pruned node. Blocks for some transactions may be missing.") }}<br><br>
									{{ _("Check this checkbox if you want to fetch missing information from block explorer.") }}
									</span>
							</tool-tip>
						</div>
						<div id="utxo-explorer">
							<br>
							{{ _("Block explorer URL:") }}
							{% include "components/explorer_select.jinja" %}
							<span class="warning" id="utxo-warning" data-style="display: inline-block; max-width:300px;">
								<img src="{{ url_for('static', filename='img/info_sign.svg') }}" data-style="width: 20px;"/><br>{{ _("Careful with block explorers!") }}<br>
								{{ _("This may have privacy implications!") }}<br>
								{{ _("Information fetched from the block explorer contains a list of unspent transactions of your wallet from old (pruned) blocks.") }}<br>
								{{ _('"They" will know what transactions you are interested in.') }}
							</span>
						</div>
						<script type="text/javascript">
							let utxocheckbox = document.getElementById("use_explorer");
							utxocheckbox.addEventListener('change', e=>{
								let el = document.getElementById("utxo-explorer")
								if(utxocheckbox.checked){
									el.style.display = "block";
								}else{
									el.style.display = "none";
								}
							});
						</script>
					{% endif %}
				{% endif %}
			</form>

			<h3 h3 class="mt-8">{{ _("Clear Cache") }}</h3>
			<form action="./clearcache" method="POST" class="padded" data-style="max-width: 500px">
				<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
				<button type="submit" name="action" value="clearcache" class="button">{{ _("Clear Cache") }}
					<tool-tip width="200px">
						<span slot="paragraph">
							{{ _('Each wallet maintains a cache which stores the details of transactions') }}<br>
							{{ _('in order to speed up loading of the tx-list. ') }}<br>
							{{ _('Clearing that cache is not deleting any crucial data and possible any time.') }}<br>
							{{ _('You might want to try this if your transactions look outdated.') }}<br>
							{{ _('However, expect a longer loading time after clearing the cache') }}<br><br>
						</span>
					</tool-tip>
				</button>
			</form>

			<h3 class="mt-8">{{ _("Delete wallet") }}</h3>
			<form action="./deletewallet" method="POST" class="padded" data-style="max-width: 500px">
				<input type="hidden" class="csrf-token" name="csrf_token" value="{{ csrf_token() }}"/>
				<button type="submit" id="delete_wallet" name="action" value="deletewallet" class="button bg-red-800 text-white">{{ _("Delete Wallet") }}</button>
			</form>
		</div>
	</div>
{% endblock %}

{% block scripts %} 
	<script type="text/javascript">
		
		let uploader = document.getElementById('label-uploader');
		uploader.addEventListener('upload', e => {
			let result = e.detail.result;
			console.log(result);
			document.getElementById("address_labels_data").value = result;
		});

		document.addEventListener("DOMContentLoaded", function(){
			let walletDataSpecterFormat = encodeURIComponent(`{{ wallet.to_json(for_export=True)|tojson }}`);
			document.getElementById('export_specter_format').href = "data:text/json;charset=utf-8," + walletDataSpecterFormat;
		});

		const registerMultisigOnDevice = async (fingerprint) => {
			const descriptor = '{{ wallet.descriptor }}'
			await registerMultisig(descriptor, fingerprint)
        }

		function toggleKeysList() {
			let titleButton = document.getElementById('toggle_keys_list');
			let keysList = document.getElementById('keys_list');
			if (keysList.style.display !== 'none') {
				keysList.style.display = 'none';
				titleButton.innerHTML = `{{ _("Show keys details") }}`;
			} else {
				keysList.style.display = 'block';
				titleButton.innerHTML = `{{ _("Hide keys details") }}`;
			}
		}

		function toggleKeyDisplay() {
			let slip132Checkbox = document.getElementById('use_slip_132');
			let xpubs = document.getElementsByClassName('slip132_xpub');
			let zpubs = document.getElementsByClassName('normal_xpub');
			if (slip132Checkbox.checked) {
				for (xpub of xpubs) {
					xpub.style.display = 'none';
				}
				for (zpub of zpubs) {
					zpub.style.display = 'block';
				}
			} else {
				for (xpub of xpubs) {
					xpub.style.display = 'block';
				}
				for (zpub of zpubs) {
					zpub.style.display = 'none';
				}
			}
		}

		function togglePDFExportAdvanced() {
			let advancedButton = document.getElementById(`advanced_pdf_export_toggle`);
			let advancedSettings = document.getElementById(`advanced_pdf_export_container`);
			if (advancedSettings.classList.contains("hidden")) {
				advancedSettings.classList.remove("hidden");
				advancedButton.innerHTML = `{{ _("Adjust PDF backup (advanced)") }} &#9660;`;
			} else {
				advancedSettings.classList.add("hidden");
				advancedButton.innerHTML = `{{ _("Adjust PDF backup (advanced)") }} &#9654;`;
			}
		}

		function setSettingsView(view) {
			let infoSettingsTab = document.getElementById("wallet_info_settings_tab");
			let exportSettingsTab = document.getElementById("wallet_export_settings_tab");
			let advancedSettingsTab = document.getElementById("wallet_advanced_settings_tab");
			let infoSettingsTabBtn = document.getElementById("info_settings_tab_btn");
			let exportSettingsTabBtn = document.getElementById("export_settings_tab_btn");
			let advancedSettingsTabBtn = document.getElementById("advanced_settings_tab_btn");
			switch (view) {
				case 'info':
					infoSettingsTab.style.display = 'block';
					exportSettingsTab.style.display = 'none';
					advancedSettingsTab.style.display = 'none';
					infoSettingsTabBtn.setAttribute('aria-checked', true);
					exportSettingsTabBtn.setAttribute('aria-checked', false);
					advancedSettingsTabBtn.setAttribute('aria-checked', false);
					break;
				case 'export':
					infoSettingsTab.style.display = 'none';
					exportSettingsTab.style.display = 'block';
					advancedSettingsTab.style.display = 'none';
					infoSettingsTabBtn.setAttribute('aria-checked', false);
					exportSettingsTabBtn.setAttribute('aria-checked', true);
					advancedSettingsTabBtn.setAttribute('aria-checked', false);
					break;
				case 'advanced':
					infoSettingsTab.style.display = 'none';
					exportSettingsTab.style.display = 'none';
					advancedSettingsTab.style.display = 'block';
					infoSettingsTabBtn.setAttribute('aria-checked', false);
					exportSettingsTabBtn.setAttribute('aria-checked', false);
					advancedSettingsTabBtn.setAttribute('aria-checked', true);
					break;
			}
		}

		let textarea = document.getElementById("address_labels_data");

		document.addEventListener('file-upload', e => {
			let result = e.detail.result;
			textarea.value = result;
		})

		// Makes sure that the textarea for labels is cleared
		document.addEventListener("DOMContentLoaded", () => {
			let textarea = document.getElementById("address_labels_data");
			textarea.value = "";
		})

	    function scrolltoRescanBlockchain() {
			setSettingsView("advanced");
			document.getElementById('blockchain-rescan').scrollIntoView();
		}
		// Only called when the user comes from an empty tx list to rescan
		{% if scroll_to_rescan_blockchain %}
	        scrolltoRescanBlockchain();
	       	document.getElementById('blockchain-rescan').classList.add("animation-rescan")
	    {% endif %}
	</script>

{% endblock %}
